import 'package:flutter/material.dart';
import 'package:playtruly/common/routers/pages.dart';

/// 路由观察者
class AppRouteObserver extends NavigatorObserver {
  @override
  void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
    debugPrint('路由 => PUSH: ${route.settings.name} from ${previousRoute?.settings.name}');
    // 添加到历史记录
    RoutePages.addHistory(route.settings.name);
    super.didPush(route, previousRoute);
  }

  @override
  void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
    debugPrint('路由 => POP: ${route.settings.name} to ${previousRoute?.settings.name}');
    // 从历史记录中移除最后一项
    if (RoutePages.history.isNotEmpty) {
      RoutePages.history.removeLast();
      debugPrint('路由历史(POP后): ${RoutePages.history}');
    }
    super.didPop(route, previousRoute);
  }

  @override
  void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
    debugPrint('路由 => REPLACE: ${oldRoute?.settings.name} by ${newRoute?.settings.name}');
    // 替换历史记录中的最后一项
    if (RoutePages.history.isNotEmpty && newRoute?.settings.name != null) {
      RoutePages.history.removeLast();
      RoutePages.addHistory(newRoute?.settings.name);
    }
    super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
  }

  @override
  void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
    debugPrint('路由 => REMOVE: ${route.settings.name}');
    // 从历史记录中移除对应路由
    RoutePages.history.remove(route.settings.name);
    debugPrint('路由历史(REMOVE后): ${RoutePages.history}');
    super.didRemove(route, previousRoute);
  }
  
  @override
  void didStartUserGesture(Route<dynamic> route, Route<dynamic>? previousRoute) {
    debugPrint('路由 => GESTURE: ${route.settings.name}');
    super.didStartUserGesture(route, previousRoute);
  }
  
  @override
  void didStopUserGesture() {
    debugPrint('路由 => GESTURE STOPPED');
    super.didStopUserGesture();
  }
} 